<?php namespace sacvoyage\app;

require_once 'sacvoyage/http/Globals.php';
use \sacvoyage\http\Globals;
use \sacvoyage\domain\Resource;

class CustomApplication extends Application {

	public function __construct(Resource $resource, $config) {
		$this->_resource=$resource;
		$this->_config=$config;
	}
	
	public function serve($path) {
		if($this->_config 
		&& isset($this->_config->handler)) {
			$handler=$this->_config->handler;
		} else {
			$handler=null;
		}
		
		// js application (not supported);
		if(isset($this->_config->type)
		&& in_array(
			strtolower($this->_config->type), 
			array('js', 'javascript', 'jscript')
		)) {
			if($handler) {
				$content=$this->_getContent($this->_config->handler);
				if($content) {
					$jsApplication=new HtmlApplication($this->_resource, $content);
					$jsApplication->serve($path);
				}
			}
		} 
		
		// html application most common used
		elseif(isset($this->_config->type) && strtolower($this->_config->type)=='html') {
			$content=$this->_getContent($this->_config->handler);
			if($handler) {
				if($content) {
					$htmlApplication=new HtmlApplication(
						$this->_getContent($this->_config->handler)
					);
					$htmlApplication->serve($path);
				}
			}
		} 
		
		// just deliver data
		elseif(!isset($this->_config->type) || $this->_config->type=='static') {
			if($handler) {
				$fileApp=new FileApplication($this->_resource);
				$fileApp->serve($this->_config->handler);
			}
		} else {
			throw new InputException("{$this->_config->type}-applications not supported");
		}	

	}
	

	
	private function _getContent($handler) {
		list($collectionName, $key)=\sacvoyage\http\parse_path($handler);
		$key=\sacvoyage\http\ltrim_path($key);
		if($key) {
			$key=explode('~', $key, 2);
			if(count($key)==2) {
				list($id, $rev)=$key;
			} else {
				$id=$key[0];
				$rev=null;
			}		
		} else {
			$id=null;
			$rev=null;
		}

		# take the output of file application
		$fileApp=new FileApplication($this->_resource);
		ob_start();
		$fileApp->get($collectionName, $id, $rev);
		return ob_get_clean();
	}
	
	
}


?>
